//
//  Created by Mingliang Chen on 18/3/9.
//  illuspas[a]gmail.com
//  Copyright (c) 2018 Nodemedia. All rights reserved.
//
const Logger = require('./node_core_logger');

const EventEmitter = require('events');
const { exec } = require('child_process');
const dateFormat = require('dateformat');
const mkdirp = require('mkdirp');
const fs = require('fs');

class NodeTransSessionWaterMarker extends EventEmitter {
  constructor(conf) {
    super();
    this.conf = conf;
  }

  run() {
    let inPath = 'rtmp://localhost'  + this.conf.streamPath;
    let ouPath = inPath + 'watermarker';
    console.log('--------------------')
    console.log(ouPath)
    // let execCmd = `${this.conf.ffmpeg} -i ${inPath} -vf "movie=./logo.png [watermark]; [in][watermark] overlay=10:10 [out]" -c:v libx264 -c:a copy -f flv ${ouPath}`
    let execCmd = `${this.conf.ffmpeg} -i ${inPath} -vf "scale=640:ih*640/iw, crop=640:480" -c:v libx264 -c:a copy -f flv ${ouPath}`
    let argv = ['-i', inPath, '-vf', `'movie=./logo.png [watermark]; [in][watermark] overlay=10:10 [out]'`, '-c:v', 'libx264', '-c:a', 'copy', '-f', 'flv', ouPath];
    Logger.ffdebug(argv.toString());
    console.log(execCmd);
    this.ffmpeg_exec = exec(execCmd);
    this.ffmpeg_exec.on('error', (e) => {
      Logger.ffdebug(e);
    });

    this.ffmpeg_exec.stdout.on('data', (data) => {
      Logger.ffdebug(`FF输出：${data}`);
    });

    this.ffmpeg_exec.stderr.on('data', (data) => {
      Logger.ffdebug(`FF输出：${data}`);
    });

    this.ffmpeg_exec.on('close', (code) => {
      Logger.log('[Transmuxing end] ' + this.conf.streamPath);
      this.emit('end');
      fs.readdir(ouPath, function (err, files) {
        if (!err) {
          files.forEach((filename) => {
            if (filename.endsWith('.ts')
              || filename.endsWith('.m3u8')
              || filename.endsWith('.mpd')
              || filename.endsWith('.m4s')) {
              fs.unlinkSync(ouPath + '/' + filename);
            }
          })
        }
      });
    });
  }

  end() {
    // this.ffmpeg_exec.kill('SIGINT');
    this.ffmpeg_exec.stdin.write('q');
  }
}

module.exports = NodeTransSessionWaterMarker;